const { Role, User } = require('../models/db');

const ok = (res, data, extra = {}) => res.json({ success: true, data, ...extra });
const fail = (res, code = 500, message = '服务器错误') => res.status(code).json({ success: false, message, code });

const mapRoleToClient = (r) => ({
  id: r._id?.toString(),
  roleId: r.roleId,
  roleName: r.roleName,
  description: r.description,
  permissions: r.permissions || [],
  userCount: r.userCount,
  updatedAt: r.updatedAt ? new Date(r.updatedAt).toISOString() : undefined,
  createdAt: r.createdAt ? new Date(r.createdAt).toISOString() : undefined,
});

const mapClientToRole = (body) => ({
  roleId: body.roleId,
  roleName: body.roleName,
  description: body.description,
  permissions: body.permissions || [],
  updatedAt: new Date(),
});

// 更新角色用户数量
const updateRoleUserCount = async (roleName) => {
  const count = await User.countDocuments({ role: getRoleCode(roleName) });
  await Role.updateOne({ roleName }, { userCount: count });
  return count;
};

// 角色名称到角色代码的映射
const getRoleCode = (roleName) => {
  const mapping = {
    '系统管理员': 'admin',
    '院长': 'muster',
    '主任': 'muster',
    '讲师': 'teacher',
    '导员': 'teacher',
    '教务人员': 'user'
  };
  return mapping[roleName] || 'user';
};

exports.getAllRoles = async (req, res) => {
  try {
    const roles = await Role.find().sort({ createdAt: -1 });
    
    // 更新所有角色的用户数量
    for (const role of roles) {
      role.userCount = await updateRoleUserCount(role.roleName);
      await role.save();
    }
    
    ok(res, roles.map(mapRoleToClient));
  } catch (e) {
    fail(res, 500, e.message);
  }
};

exports.getRoleById = async (req, res) => {
  try {
    const r = await Role.findById(req.params.id);
    if (!r) return fail(res, 404, '未找到该角色');
    
    // 更新用户数量
    r.userCount = await updateRoleUserCount(r.roleName);
    await r.save();
    
    ok(res, mapRoleToClient(r));
  } catch (e) {
    fail(res, 500, e.message);
  }
};

exports.createRole = async (req, res) => {
  try {
    const payload = mapClientToRole(req.body || {});
    if (!payload.roleId || !payload.roleName) {
      return fail(res, 400, '缺少必要字段: roleId | roleName');
    }
    
    const exist = await Role.findOne({ $or: [{ roleId: payload.roleId }, { roleName: payload.roleName }] });
    if (exist) return fail(res, 400, '角色ID或名称已存在');
    
    const count = await updateRoleUserCount(payload.roleName);
    payload.userCount = count;
    
    const created = await Role.create(payload);
    ok(res, mapRoleToClient(created));
  } catch (e) {
    fail(res, 500, e.message);
  }
};

exports.updateRole = async (req, res) => {
  try {
    const payload = mapClientToRole(req.body || {});
    payload.updatedAt = new Date();
    
    // 如果角色名称改变，更新用户数量
    if (payload.roleName) {
      payload.userCount = await updateRoleUserCount(payload.roleName);
    }
    
    const updated = await Role.findByIdAndUpdate(req.params.id, payload, { new: true });
    if (!updated) return fail(res, 404, '未找到该角色');
    ok(res, mapRoleToClient(updated));
  } catch (e) {
    fail(res, 500, e.message);
  }
};

exports.deleteRole = async (req, res) => {
  try {
    const deleted = await Role.findByIdAndDelete(req.params.id);
    if (!deleted) return fail(res, 404, '未找到该角色');
    ok(res, { id: req.params.id });
  } catch (e) {
    fail(res, 500, e.message);
  }
};

